package com.example.bee_work_3.net_request;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


/**
 * @author Frontman
 * @data create on 2019/6/2
 * 两种不同的请求方式
 * @see MyNetworkRequest#byPost()
 * @see MyNetworkRequest#byGet()
 */
public class MyNetworkRequest {

    public static final String GET = "GET";
    public static final String POST = "POST";

    //请求延时，默认8000ms
    private static final int mReadTimeout = 8000;
    private static final int mConnectTimeout = 8000;
    private URL mUrl;
    private String mType = "GET";
    private String mParam = "";
    private boolean mCache = false;

    public MyNetworkRequest() {
    }

    public MyNetworkRequest(URL url) {
        this.mUrl = url;
        this.mType = "GET";
    }

    /***
     * @param url 连接地址/接口
     * @param type 连接类型
     */
    public MyNetworkRequest(URL url, String type) {
        this.mUrl = url;
        this.mType = type;
    }

    /**
     * @param param 发送的额外信息  POST
     **/
    public MyNetworkRequest(String param, URL url) {
        this.mType = "POST";
        this.mUrl = url;
        this.mParam = param;
    }

    public MyNetworkRequest(String param, URL url, String type) {
        this.mType = type;
        this.mUrl = url;
        this.mParam = param;
    }

    public void setUrl(URL url) {
        this.mUrl = url;
    }

    public static URL ToUrl(String str) {
        URL url = null;
        try {
            url = new URL(str);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return url;
    }

    public void setCaches(boolean judgement) {
        if ((judgement)) {
            mCache = true;
        } else {
            mCache = false;
        }
    }

    public MyJsonObject connect() {

        switch (mType) {
            case GET:
                return getResult(byGet());
            case POST:
                return getResult(byPost());
            default:
                Log.e("MyConnect",
                        "Error type ,unknown type ;type is get or post;");
                return null;
        }
    }

    /**
     * By Get
     **/
    private String byGet() {
        HttpURLConnection httpURLConnection = null;
        BufferedReader reader = null;
        String json = "";

        try {
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();
            httpURLConnection.setRequestMethod(mType);
            httpURLConnection.setReadTimeout(mReadTimeout);
            httpURLConnection.setConnectTimeout(mConnectTimeout);
            InputStream in = httpURLConnection.getInputStream();
            if (httpURLConnection.getResponseCode() != 200) {
                Log.e("Https error", "连接失败,错误代码：" + httpURLConnection.getResponseCode());
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(in));
            String temp;
            while ((temp = reader.readLine()) != null) {
                json += temp;
            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return json;
    }

    /**
     * By Post
     * 待修改，
     **/
    private String byPost() {
        HttpURLConnection httpURLConnection = null;
        DataOutputStream param = null;
        BufferedReader reader = null;
        String json = "";
        try {
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();


            //设置请求属性
            httpURLConnection.setRequestProperty("Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");//这个看不懂
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");//长连接


            //打开输入输出,设置缓存,连接方式
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(mCache);
            httpURLConnection.setRequestMethod(mType);

            //传递参数
            param = new DataOutputStream(httpURLConnection.getOutputStream());
            param.writeBytes(mParam);
            param.flush();
            param.close();

            //这个返回的成功码一般是200吧，不知道会不会遇到不一样的
            if (httpURLConnection.getResponseCode() != 200) {
                return null;
            }
            String temp = "";
            reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
            while ((temp = reader.readLine()) != null) {
                json += temp;
            }
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        }
        return json;
    }

    private MyJsonObject getResult(String json) {
        return json == null ? null : new MyJsonObject(json);
    }

}
